package install

import (
	"fmt"
	"io/ioutil"
	"path"
	"strconv"
	"strings"

	"gitee.com/shaddy/k3sinstall/mylog"
	"gopkg.in/yaml.v2"
)

func AddHookNodes(config *K3sConfig, node []string) {
	mylog.Info.Printf("开始添加节点 ..\n")
	for n := range node {
		for m := range config.Nodes {
			if config.Nodes[m] == node[n] {
				mylog.Error.Panicf("不能添加已经存在的节点 %s", node[n])
				break
			}
		}
	}
	oldn := len(config.Nodes)
	for n := range node {
		config.Nodes = append(config.Nodes, node[n])
		config.NHoseName = append(config.NHoseName, config.NodeNameTag+strconv.Itoa(oldn+n))
		synRunCmd(node[n], config.User, config.Passwd, fmt.Sprintf("hostnamectl set-hostname %s", config.NodeNameTag+strconv.Itoa(oldn+n)))
	}
	config.runCmd(node, `systemctl stop firewalld && systemctl disable firewalld`)
	config.runCmd(node, `sed -i 's#SELINUX=enforcing#SELINUX=disabled#g' /etc/selinux/config && setenforce 0`)
	config.runCmd(node, `cat > /etc/resolv.conf << EOF
nameserver 8.8.8.8
EOF`)
	// for install
	mytoken := synRunCmd(config.Masters[0], config.User, config.Passwd, "cat /var/lib/rancher/k3s/server/node-token")
	if mytoken == "" {
		mylog.Error.Panic("安装时token获取失败")
	} else {
		mytoken = strings.Replace(mytoken, "\n", "", -1)
	}
	for m := range node {
		config.synTransFileForOneNode(node[m])

	}
	config.runCmd(node, fmt.Sprintf("tar -xzvf %s", path.Join(config.WorkDir, config.PkgFile)))
	config.runCmd(node, fmt.Sprintf("echo \"%s  registry.hbfec.com\" >> /etc/hosts", getIp(config.Masters[0])))
	config.runCmd(node, fmt.Sprintf("mkdir -p /var/lib/rancher/k3s/agent/images/ && cp %s /var/lib/rancher/k3s/agent/images/ && cp %s /usr/local/bin", path.Join(config.WorkDir, "k3s", config.ImgFile), path.Join(config.WorkDir, "k3s", "k3s")))
	config.runCmd(node, fmt.Sprintf("mkdir -p /etc/rancher/k3s/ && cp %s /etc/rancher/k3s/", path.Join(config.WorkDir, "k3s", "registries.yaml")))
	config.runCmd(node, fmt.Sprintf("INSTALL_K3S_SELINUX_WARN=true K3S_URL=https://%s:6443 K3S_TOKEN=%s %s", getIp(config.Masters[0]), mytoken, path.Join(config.WorkDir, "k3s", "install.sh")))
	// for soft
	//config.runCmd(node, fmt.Sprintf("ctr i import  %s", path.Join(config.WorkDir, "k3s", "kuboard.tar")))

	context, err := yaml.Marshal(config)
	if err != nil {
		mylog.Error.Fatalf("解析配置文件错误 err: %s", err.Error())
	}
	err = ioutil.WriteFile(config.ConfigFile, context, 0777)
	if err != nil {
		mylog.Warning.Printf("写入配置文件错误 configfile: %s err: %s \n", config.ConfigFile, err.Error())
	}
}
